from sys import path

if 'configs' not in path:
    path.append(r'configs')

from api.salt_api import SaltAPI
from oms import settings
import threading

asset_info = []


def get_server_asset_info(tgt):
    '''
    Salt API得到资产信息，进行格式化输出
    '''
    global asset_info
    info = []
    info_dict = {}
    sapi = SaltAPI(apiurl=settings.SALT_API['apiurl'], username=settings.SALT_API['user'],
                   password=settings.SALT_API['password'])
    ret = sapi.remote_noarg_execution(tgt, 'grains.items')
    # manufacturer = ret['manufacturer']
    # info.append(manufacturer)
    info_dict['manufacturer'] = ret['manufacturer']

    # productname = ret['productname']
    # info.append(productname)
    info_dict['productname'] = ret['productname']

    # serialnumber = ret['serialnumber']
    # info.append(serialnumber)
    info_dict['serialnumber'] = ret['serialnumber']

    # cpu_model = ret['cpu_model']
    # info.append(cpu_model)
    info_dict['cpu_model'] = ret['cpu_model']

    # num_cpus = int(ret['num_cpus'])
    # info.append(num_cpus)
    info_dict['cpu_nums'] = int(ret['num_cpus'])

    # num_gpus = int(ret['num_gpus'])
    # info.append(num_gpus)
    info_dict['cpu_groups'] = int(ret['num_gpus'])
    info_dict['cpuarch'] = ret['cpuarch']

    # mem_total = str(round(int(ret['mem_total']) / 1000.0, ))[:-2] + 'G'
    # info.append(mem_total)
    if (ret['mem_total'] / 1000.0) < 1:
        info_dict['mem_total'] = str(ret['mem_total']) + 'M'
    else:
        info_dict['mem_total'] = str(round(int(ret['mem_total']) / 1000.0, )) + 'G'

    # disk_size = ret['disk_size']
    # info.append(disk_size)

    # raidlevel = ret['raidlevel']
    # info.append(raidlevel)

    # id = ret['id']
    # info.append(id)
    info_dict['id'] = ret['id']  # lan_ip = ret['lan_ip'][0]
    # info.append(lan_ip)

    # lan_mac = ret['hwaddr_interfaces']['eth0']
    # info.append(lan_mac)
    info_dict['lan_mac'] = ret['hwaddr_interfaces']['eth0']
    info_dict['ip_v4'] = str(ret['ip4_interfaces']['eth0']).strip("[").strip("]").strip("'")

    # sys_ver = ret['oz'] + ret['osrelease'] + '-' + ret['osarch']
    # info.append(sys_ver)
    info_dict['sys_ver'] = ret['osrelease'] + '-' + ret['osarch']
    info_dict['os_type'] = ret['os']
    info_dict['os_version'] = ret['osrelease']
    info_dict['os_arch'] = ret['osarch']

    # virtual = ret['virtual']
    # info.append(virtual)
    info_dict['virtual'] = ret['virtual']

    # idc_name = ret['idc_name']
    # info.append(idc_name)

    # print(info_dict)
    # asset_info.append(info)
    asset_info.append(info_dict)


def multitle_collect(tgt):
    """
    
    :param tgt: 
    :return: 
    """
    global asset_info
    # 全局变量置空,避免多次请求的时候返回结果叠加
    aseet_info = []
    threads = []
    loop = 0
    numtgt = len(tgt)
    for i in range(0, numtgt, 2):
        nkeys = range(loop * 2, (loop + 1) * 2, 1)
        # 实例化线程
        for i in nkeys:
            if i >= numtgt:
                break
            else:
                t = threading.Thread(target=get_server_asset_info, args=(tgt[i],))
                threads.append(t)
        # 启动线程
        for i in nkeys:
            if i >= numtgt:
                break
            else:
                threads[i].start()
        # 等待并发线程结束
        for i in nkeys:
            if i >= numtgt:
                break
            else:
                threads[i].join()
        loop = loop + 1
    return asset_info


def check_asset_status(ip):
    """
    检查资产状态
    :return: 
    """
    # salt_api = SaltAPI(apiurl='https://10.10.0.31:8000', username='saltapi', password='saltapi')
    sapi = SaltAPI(apiurl=settings.SALT_API['apiurl'], username=settings.SALT_API['user'],
                   password=settings.SALT_API['password'])
    ret = sapi.remote_noarg_execution(ip, 'test.ping')
    ret = bool(ret)
    if ret:
        return 1
    else:
        return 0
